﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tea;
using System.Collections;
using System.IO;
using Tea.Utils;
using System.Web.UI.WebControls;
using DingTalk.Api;
using DingTalk.Api.Request;
using DingTalk.Api.Response;
using HeqinSjsc2024.Class.DingApi.Response;
using FastJSON;
using Newtonsoft.Json;
using HeqinSjsc2024.Data;
using HeqinSjsc2024.Class.Models.DtoDing;






namespace HeqinSjsc2024
{
    public partial class frmMain : Form
    {
        /// <summary>
        /// 
        /// </summary>
        /// 
        #region 静态变量定义区
        public static string _SqlConTxt = "Data Source=192.168.1.153;Initial Catalog=HqtxManager;Persist Security Info=True;User ID=sa;Password=router@2010";

        //钉钉相关配置信息
        public static readonly long _ErrNoteDingGroupID = 975581610L;
        public static readonly string _ErrNoteRobotCode = "dingpgolajwotp7nxs15";


        private static string _dingAppKey = "ding5e8htpreemdfawsb";
        private static string _dingAppSecret = "PeCW5_Uwi2lLwzZ50Bbaet80GpIbk_3S3SjW-Z6TeMNf1LM5PKywWWjHtC6TOgQL";
        private static string _dingProcessCodeSjsc = "PROC - C7507025 - E24F - 40E3 - 83FE-5A9388729D14";
        
        //Token参数定义区
        private static bool IsDingTokenEnable = false;
        private static string DingToken;
        private static bool IsGetDingTokenRuning = false;
        private static bool IsGetDingTokenRun = false;

        //更新部门列表
        private static bool IsUpdateDingDepListRuning = false;
        private static bool IsUpdateDingDepListRun = false;
        private static bool HasErrUpdateDingDepList = false;
        private static uint CountUpdateDingDepList = 0;
        private static string VerNoUpdateDingDep = "";

        //更新人员信息
        private static bool IsUpdateDingEmployeeRuning = false;
        private static bool IsUpdateDingEmployeeRun = false;
        private static bool HasErrUpdateDingEmployee = false;
        private static uint CountUpdateDingEmployee = 0;

        //更新审批实例清单
        private static bool IsUpdateInstanceListRuning = false;
        private static bool IsUpdateInstanceListRun = false;
        private static bool HasErrUpdateInstanceList = false;
        private static uint CountUpdateInstanceList = 0;

        //更新审批实列详情
        private static bool IsUpdateInstanceRuning = false;
        private static bool IsUpdateInstanceRun = false;
        private static bool HasErrUpdateInstance = false;
        private static uint CountUpdateInstance = 0;

        //删除审批实列
        private static bool IsDeleteInstanceRuning = false;
        private static bool IsDeleteInstanceRun = false;
        private static bool HasErrDeleteInstance = false;
        private static uint CountDeleteInstance = 0;
        #endregion 静态变量定义结束




        public frmMain()
        {
            InitializeComponent();
        }

        public static AlibabaCloud.SDK.Dingtalkoauth2_1_0.Client CreateClient()
        {
            AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config();
            config.Protocol = "https";
            config.RegionId = "central";
            return new AlibabaCloud.SDK.Dingtalkoauth2_1_0.Client(config);
        }
        /// <summary>
        /// GetDingTalkToken
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GetDingTalkToken(string dingTalkAppKey, string dingtalkAppSecret)
        {
            AlibabaCloud.SDK.Dingtalkoauth2_1_0.Client client = CreateClient();
            AlibabaCloud.SDK.Dingtalkoauth2_1_0.Models.GetAccessTokenRequest getAccessTokenRequest = new AlibabaCloud.SDK.Dingtalkoauth2_1_0.Models.GetAccessTokenRequest
            {
                AppKey = dingTalkAppKey,
                AppSecret = dingtalkAppSecret,
                //test
            };

            try
            {
                AlibabaCloud.SDK.Dingtalkoauth2_1_0.Models.GetAccessTokenResponse rsp = client.GetAccessToken(getAccessTokenRequest);
                Console.WriteLine(rsp.Body.AccessToken);
            
                
            }
            catch (TeaException err)
            {
                if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message))
                {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                }
            }
            catch (Exception _err)
            {
                TeaException err = new TeaException(new Dictionary<string, object>
                {
                    { "message", _err.Message }
                });
                if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message))
                {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                }
            }


        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dingTalkAppKey"></param>
        /// <param name="dingtalkAppSecret"></param>
        /// 



        #region 更新部门列表 UpdateDingDepList

        //isTopLevel指得是在递归中是否是顶层
        private void UpdateDingDepList(string dingToken, long parentID, bool isRun, ref bool isRuning, ref bool hasErr, ref uint runCount, bool isTopLevel )
        {
            //顶层
            if (isRun && isTopLevel && !isRuning)
            {
                VerNoUpdateDingDep = DateTime.Now.ToString("yyyyMMddHHmmss");
                IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
                OapiV2DepartmentListsubRequest req = new OapiV2DepartmentListsubRequest();
                req.DeptId = 1L;


                try
                {
                    OapiV2DepartmentListsubResponse rsp = client.Execute(req, dingToken);
                    Console.WriteLine(rsp.Body);
                    //这里取出来了数据,查看是否有返回结果及错误
                    DingResListSubID dingResListSubID = JsonConvert.DeserializeObject<DingResListSubID>(rsp.Body);
                    //错误返回码正确的
                    if (dingResListSubID.Errcode == 0 )
                    {
                        foreach (var subDep in dingResListSubID.Result)
                        {
                            DtoDingDepListService dtoDepListService = new DtoDingDepListService();
                            var dtoSubDep = dtoDepListService.GetDepartmentByDeptId(subDep.DeptId);
                            //数据存在
                            if (dtoSubDep != null)
                            {

                            }
                            //数据不存在，写入新的数据
                            else
                            {
                                var newDtoSubDep = new DtoDingDepList
                                {
                                    DeptId = subDep.DeptId.ToString(),
                                    Name = subDep.Name,
                                    ParentId = subDep.ParentId.ToString(),
                                    IsActive = true,
                                    UpdateTime = DateTime.Now,
                                    VerNo = VerNoUpdateDingDep
                                };
                                dtoDepListService.AddDepartment(newDtoSubDep);  
                            }
                        }
                    }
                    //错误码错误的处理
                    else
                    {
                        HasErrUpdateDingDepList = true; 


                    }

                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error: {ex.Message}");  
                    throw;
                }

         //       foreach (var item in collection)
                

                
              //  UpdateDingDepList(DingToken, 2, IsUpdateDingDepListRun, ref IsUpdateDingDepListRuning, ref HasErrUpdateDingDepList, ref CountUpdateDingDepList, false);

            }
            //递归的
            else if (isRun && !isTopLevel && isRuning)
            {
                IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
                OapiV2DepartmentListsubRequest req = new OapiV2DepartmentListsubRequest();
                req.DeptId = 1L;
                OapiV2DepartmentListsubResponse rsp = client.Execute(req, dingToken);
                Console.WriteLine(rsp.Body);
                UpdateDingDepList(DingToken, 2, IsUpdateDingDepListRun, ref IsUpdateDingDepListRuning, ref HasErrUpdateDingDepList, ref CountUpdateDingDepList, false);
   

            }


            //

        }
        #endregion 结束更新部门


        #region 更新人员信息 UpdateDingEmployee
        private void UpdateDingEmployee(string dingToken, string parentID, bool isRun, ref bool isRuning, ref bool hasErr, ref uint runCount)
        {

        }
        #endregion 更新人员信息


        private void timerGetDingTalkToken_Tick(object sender, EventArgs e)
        {
           // this.GetDingTalkToken(sender, e);这里暂停
           
        }

        private void button10_Click(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 部门的Debug按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDepDebug_Click(object sender, EventArgs e)
        {
            UpdateDingDepList(edtDingToken.Text, 1, IsUpdateDingDepListRun, ref IsUpdateDingDepListRuning, ref HasErrUpdateDingDepList, ref CountUpdateDingDepList, true);

        }

        private void btnChangeToken_Click(object sender, EventArgs e)
        {
            DingToken = edtDingToken.Text;
        }

        private void button11_Click(object sender, EventArgs e)
        {
            
        }
        #region 单击选项更改
        //部门更新isRun按钮
        private void rbtDepRun_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtDepRun.Checked)
            {
                IsUpdateDingDepListRun = true;

            } else
            {
                IsUpdateDingDepListRun = false;
            }
        }
        #endregion
    }
}
